package com.superfish.cutieshop.activities;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.TextView;

import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.superfish.cutieshop.BaseActivity;
import com.superfish.cutieshop.BaseApp;
import com.superfish.cutieshop.BaseConfig;
import com.superfish.cutieshop.R;
import com.superfish.cutieshop.been.ShareContent;
import com.superfish.cutieshop.been.Version;
import com.superfish.cutieshop.dialog.AppDialog;
import com.superfish.cutieshop.dialog.AppLoading;
import com.superfish.cutieshop.dialog.BaseDialog;
import com.superfish.cutieshop.dialog.ShareDialog;
import com.superfish.cutieshop.file.FileUtils;
import com.superfish.cutieshop.http.HttpStores;
import com.superfish.cutieshop.http.ZokeParams;
import com.superfish.cutieshop.parser.GsonVersion;
import com.superfish.cutieshop.utils.CommonUtil;
import com.superfish.cutieshop.utils.CutieToast;
import com.superfish.cutieshop.utils.DownloadVersionApk;
import com.superfish.cutieshop.utils.DownloadVersionListener;
import com.superfish.cutieshop.utils.HttpParams;
import com.superfish.cutieshop.utils.PersistTool;
import com.superfish.cutieshop.utils.SimpleAsync;
import com.superfish.cutieshop.utils.TimeUtils;

import java.io.File;

@ContentView(R.layout.activity_settings)
public class SettingsActivity extends BaseActivity {

    @ViewInject(R.id.toolbar)
    private Toolbar mToolbar;
    @ViewInject(R.id.version_tips)
    private TextView mVersionTips;//版本提示信息
    @ViewInject(R.id.cache_size)
    private TextView mCacheSize;//缓存大小
    private long cacheSize;
    @ViewInject(R.id.switch_off)
    private TextView mSwitchTv;

    private AppLoading loading;

    private ShareDialog shareDialog;

    public static void open(Activity act) {
        Intent i = new Intent(act, SettingsActivity.class);
        open(act, i);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mToolbar.setTitle("");
        setAppTitle(R.string.menu_settings);
        mToolbar.setNavigationIcon(R.drawable.btn_back_bar);
        //动态设置颜色 根据当前星期时间设置
        mToolbar.setBackgroundColor(getResources().getColor(TimeUtils.aTheme()));
        getStatusBar().setBackgroundColor(getResources().getColor(TimeUtils.aTheme()));
        setSupportActionBar(mToolbar);
        mCacheSize.setVisibility(View.GONE);
        fetchCacheSize();
        boolean isSwitch = PersistTool.getBoolean(BaseConfig.ShareKey.NOTIFY_SWITCH, false);
        mSwitchTv.setSelected(isSwitch);
        shareDialog = new ShareDialog(this, ShareContent.getMainShareContent());
    }


    /**
     * 通知开关点击
     **/
    @OnClick(R.id.switch_off)
    public void onClickSwitch(View v) {
        mSwitchTv.setSelected(!mSwitchTv.isSelected());
        //如果是选中状态就close
        PersistTool.saveBoolean(BaseConfig.ShareKey.NOTIFY_SWITCH, mSwitchTv.isSelected());
//        CommonUtil.changeNotify(this);
        CommonUtil.saveRed(getApplicationContext(), mSwitchTv.isSelected());
    }


    @OnClick(R.id.score)
    public void onClickScore(View v) {
        //给购萌早报打分
        BaseApp.openAppMarketsAtMyDetails(SettingsActivity.this, 0);
    }

    @OnClick(R.id.protocol)
    public void onClickProtocol(View v) {
        //用户协议
//        WebActivity.open(SettingsActivity.this, BaseConfig.AGREEMENT_URL, getResources().getString(R.string.setttings_protocol), true);
        shareDialog.show();
    }

    @OnClick(R.id.buyer)
    public void onBuyer(View v) {
        //买手征集计划
        WebActivity.open(SettingsActivity.this, BaseConfig.BUYER, getResources().getString(R.string.menu_buy_tips), true);
    }

    @OnClick(R.id.reviews)
    public void onReviews(View v) {
        ReviewsActivity.open(SettingsActivity.this);
    }


    @OnClick(R.id.cache)
    public void onClickCache(View v) {
        //清理缓存
        if (cacheSize == 0) {
            CutieToast.show(getApplicationContext(), R.string.toast_show_clear_cache);
            return;
        }
        clearCache();
    }

    @OnClick(R.id.version)
    public void onClickVersion(View v) {
        //版本更新
        loading = new AppLoading(SettingsActivity.this);
        loading.setTips(R.string.version_checking);
        loading.show();
        fetchVersion();
    }

    /**
     * 版本检测
     **/
    private void fetchVersion() {
        ZokeParams params = HttpParams.getDefaultByGet(BaseConfig.UrlBank.version, mHashCode);
        HttpStores.getInstense().get(params);
    }

    @Override
    public void onSuccess(ZokeParams out) {
        super.onSuccess(out);
        loading.dismiss();
        String url = out.getUrl();
        String result = (String) ((ResponseInfo) out.getResult()).result;
        if (url.equals(BaseConfig.UrlBank.version)) {
            GsonVersion gv = new GsonVersion().fromJson(result);
            if (gv.info == null || gv.error_code != 0) {
                return;
            }
            checkCode(gv.info);
            return;
        }
    }


    private void checkCode(final Version vs) {
        if (vs == null)
            return;
        try {
            int serverCode = vs.ver;
            int clientCode = CommonUtil
                    .getClientVersionCode(getApplicationContext());
            if (serverCode <= clientCode) {
                //
                CutieToast.show(SettingsActivity.this, R.string.version_news);
                return;
            }
            showNorDialog(vs);
        } catch (Exception e) {

        }


        return;

    }


    /**
     * 弹出非强制更新框
     **/
    private void showNorDialog(final Version vs) {
        final AppDialog mNorDialog = new AppDialog(SettingsActivity.this);
        String str = getResources().getString(R.string.versionDownloadtitle);
        str = String.format(str, "" + vs.name);
        mNorDialog.setDialogTitle(str);
        mNorDialog.setSubTitle(vs.describe);
//        mNorDialog.setContent(vs.describe);
        mNorDialog.setLeftClick(new BaseDialog.LeftClickLinstener() {
            @Override
            public void onClickLeft(View view) {
                mNorDialog.dismiss();
            }
        });
        //
        mNorDialog.setRightClick(new BaseDialog.RightClickLinstener() {
            @Override
            public void onClickRight(View view) {
                downloadApk(vs.url);
                mNorDialog.dismiss();
            }
        });
        // --
        mNorDialog.setLeftText(getResources().getString(
                R.string.versionDownloadcancle));
        mNorDialog.setRightText(getResources().getString(
                R.string.versionDownload));
        mNorDialog.show();
    }

    private void downloadApk(String url) {
        // 防止重复下载
        if (!DownloadVersionApk.getInstense(SettingsActivity.this).isdoing) {
            DownloadVersionApk.getInstense(SettingsActivity.this).downLoad(url);
            DownloadVersionApk.getInstense(SettingsActivity.this).setListener(
                    new DownloadVersionListener() {
                        @Override
                        public void onSuccess(File file) {
                            // 下载完 执行安装
                            CommonUtil
                                    .installApk(file, getApplicationContext());
                        }
                    });
        } else {
            // 提示下
            CutieToast.show(getApplicationContext(), R.string.versionCheckedToast);
        }

    }


    @Override
    public void onFails(ZokeParams out) {
        super.onFails(out);
        CutieToast.showNetFailed(getApplicationContext());
        loading.dismiss();
    }

    private void clearCache() {
        new SimpleAsync(new SimpleAsync.SimpleCallback() {
            @Override
            public void onPrepare() {

            }

            @Override
            public void onStart() {
                String cacheDir = BaseApp
                        .getCacheDir(getApplicationContext());
                FileUtils.delAllFile(cacheDir);
            }

            @Override
            public void onFinish() {
                //提示
                String toast = getResources().getString(R.string.setttings_cache_tips);
                toast = String.format(toast,
                        FileUtils.formatFileSize(cacheSize));
                CutieToast.show(getApplicationContext(), toast);
                cacheSize = 0;
                mCacheSize.setVisibility(View.GONE);
            }
        }).execute();
    }

    private void fetchCacheSize() {
        new SimpleAsync(new SimpleAsync.SimpleCallback() {
            String cacheDir = "";

            @Override
            public void onPrepare() {
            }

            @Override
            public void onStart() {
                cacheDir = BaseApp.getCacheDir(getApplicationContext());
                cacheSize = FileUtils.getCacheSize(cacheDir);
            }

            @Override
            public void onFinish() {
                if (cacheSize == 0)
                    return;
                mCacheSize.setVisibility(View.VISIBLE);
                mCacheSize.setText(FileUtils.formatFileSize(cacheSize));
            }
        }).execute();
    }
}
